const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");

const indexRoute = require("./server/routes/server.index.route.js");

// 实例化express
const app = express();

// 配置打印logger
app.use(logger("dev"));

// 配置静态文件路径
app.use(express.static(path.join(__dirname, "static")));

// 解析cookie
app.use(cookieParser());

// 解析application/json格式数据
app.use(bodyParser.json());

// 解析application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));

// 配置路由
app.use("/", indexRoute);

// 处理404错误
app.use((req, res, next)=>{
	let err = new Error("Error: 404, the source is not founded!");
	err.status = 404;
	next(err);
});

// 处理500错误
app.use((err, req, res, next)=>{
	res.status(err.status || 500).send(err.message);
	next();
});

module.exports = app;